<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function loginAction()
    {
        // action body
        $layout = Zend_Layout::getMvcInstance();
        $layout->setLayout("login");
        $this->view->headTitle("Đăng nhập");
        $form = new Application_Form_Login();
        
        if($this->_request->isPost()) {
            if($form->isValid($_POST)) {
                $data = $form->getValues();
                $authAdapter = new Zend_Auth_Adapter_DbTable(null, "users", "username", "password");
                $authAdapter->setIdentity($data['username'])
                            ->setCredential(md5($data['password']));
                $result = $authAdapter->authenticate();
                if($result->isValid()) {
                    $auth = Zend_Auth::getInstance();
                    $store = $auth->getStorage();
                    $store->write($authAdapter->getResultRowObject(array(
                        "idUsers","Username","Fullname","Groups"
                    )));
                    return $this->_redirect($this->view->url(array(
                        "controller"=>"index", 'action'=>"index"
                    ), null, true));
                }else{
                    $form->username->addError("Sai tài khoản hoặc mật khẩu");
                }
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        // action body
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        return $this->_redirect($this->view->url(array(
            "controller"=>"user", 'action'=>"login"
        ), null, true));
    }


}





